const bcrypt = require('bcrypt');
const Router = require('@koa/router');

const {addUser, findOneUser} = require('../db/user');

const router = new Router();

router.post('/auth/log', async ctx => {
  const {mail, pass} = ctx.request.body;
  console.log(mail, pass);

  let user = await findOneUser({mail});

  if (!user) {
    ctx.body = {code: 'LOG.MISMATCH'};
    return;
  }

  const validated = bcrypt.compareSync(pass, user.pass);

  if (!validated) {
    ctx.body = {code: 'LOG.MISMATCH'};
    return;
  }

  ctx.body = {ok: true, role:'USER'};
  ctx.status = 200;
})
  
router.post('/auth/reg', async (ctx) => {

  const {mail, pass} = ctx.request.body;

  let user = await findOneUser({mail});

  if (user) {
    ctx.body = {code:'REG.EXISTING', desc: '用户名已经存在'};
    return;
  }

  addUser({mail, pass});

  ctx.body = {ok: true};
  ctx.status = 200;
});

module.exports = router;